package com.zhengb.algorithmdemo.leetcode.common;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 日志限流器
 * https://leetcode-cn.com/problems/logger-rate-limiter/
 *
 * @author zhengbo
 * @date 2020/3/21
 */
public class LogRaterLimit {

    private static class LogCache extends LinkedHashMap<String, Integer> {

        private final static long max = 1000;

        @Override
        public Integer put(String key, Integer value) {
            return super.put(key, value);
        }

        @Override
        protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) {
            return size() > max;
        }
    }

    private LogCache LOG_CACHE;

    public LogRaterLimit() {
        LOG_CACHE = new LogCache();
    }


    public boolean shouldPrintMessage(int timestamp, String message) {

        Integer messageCache = LOG_CACHE.get(message);
        if (messageCache != null) {
            if (Math.abs(messageCache - timestamp) < 10) {
                return false;
            }
        }

        LOG_CACHE.put(message, timestamp);

        return true;

    }

    public static void main(String[] args) {

        LogRaterLimit logger = new LogRaterLimit();

        System.out.println(logger.shouldPrintMessage(100, "bug"));
        System.out.println(logger.shouldPrintMessage(100, "bug"));
//        System.out.println(logger.shouldPrintMessage(3, "foo"));
//        System.out.println(logger.shouldPrintMessage(8, "bar"));
//        System.out.println(logger.shouldPrintMessage(10, "foo"));
//        System.out.println(logger.shouldPrintMessage(11, "foo"));


    }
}
